<template>
	<div>
		<div class="search-wrapper">
			<div class="search">
				<van-icon name="search" />
				<input
					type="text"
					v-model="inputValue"
					placeholder="搜索歌手、歌曲、专辑"
					ref="a"
					@keyup.enter="enter"
					@input="search"
				/>
				<van-icon name="cross" size="small" @click="empty" class="btn"/>
			</div>
		</div>
		<keep-alive>
			<component
				:is="comName"
				@add="getValue"
				:inputValue="inputValue"
			></component>
		</keep-alive>
	</div>
</template>
<script>
import * as tool from "@/utils";
// 搜索之前
import HotSearch from "./pages/hot-search";
// 搜索之后
import MatchPage from "./pages/match-page";
import eventBus from "@/event-bus";
// 模糊查询
import FuzzyQuery from "./pages/fuzzy-query";
// 防抖;
const getSearchSuggest = tool.debounce(function () {
	// 请求搜索建议
	eventBus.$emit("updateGetOnSearchList", this.inputValue);
}, 1000);

export default {
	data() {
		return {
			comName: "HotSearch",
			inputValue: "",
		};
	},
	components: {
		HotSearch,
		MatchPage,
		FuzzyQuery,
	},
	mounted() {
		this.btn();
	},
	methods: {
		empty() {
			this.inputValue = "";
			this.comName = HotSearch;
		},
		enter() {
			this.comName = MatchPage;
			if (!this.inputValue) {
				getSearchSuggest.call(this);
				this.comName = HotSearch;
			}
			eventBus.$emit("updateMatchList", this.inputValue);
			eventBus.$emit("updateMultimatchList", this.inputValue);
		},
		search() {
			this.comName = FuzzyQuery;
			getSearchSuggest.call(this);
		},
		getValue(value) {
			this.inputValue = value;
			this.enter();
		},
		async btn() {
			await this.$nextTick();
			this.$refs.a.focus();
		},
	},
};
</script>
<style scoped>
.search-wrapper {
	display: flex;
	align-items: center;
	width: 100%;
	height: 50px;
	border-bottom: 1px solid #aaa;
	box-sizing: border-box;
}
.search {
	height: 30px;
	display: flex;
	align-items: center;
	flex: 1;
	margin: 0 12px;
	border-radius: 15px;
	background-color: #eee;
}
.search > * {
    margin-left: 8px;
}
.search input {
    flex: 1;
	width: 80%;
	font-size: 12px;
	outline: none;
	border: none;
	background-color: #eee;
}
.btn {
    margin-right: 8px;
}
</style>